//
// Created by 吴喆 on 2020/3/6.
//

#include "Animation.h"
#include "../util/Console.h"

Animation::Animation(int interval, bool isLoop) : interval(interval), lastFrameNo(0), count(0), isLoop(isLoop) {
    time = CTime::getInstance();
    lastTime = 0;

};

void Animation::addFrame(Texture2D *texture) {
    textures.push_back(texture);
}

Texture2D *Animation::getCurrentFrame() {
    if (!isOver) {
        return textures[lastFrameNo];
    } else {
        return textures[textures.size() - 1];
    }

}

void Animation::setInterval(int interval) {
    Animation::interval = interval;
}

void Animation::refresh() {
    lastTime = 0;
    lastFrameNo = 0;
    isOver = false;
    count = 0;
    flag = false;
}

void Animation::update() {
    if (textures.empty()) {
        Console::ERR("Animation textures is empty");
    }
    if (lastTime == 0) {
        lastTime = time->getCurrentFrame();
    }

    if ((time->getCurrentFrame() - lastTime) * 1000 >= interval) {

        ++count;
        lastTime = time->getCurrentFrame();
        lastFrameNo = (lastFrameNo + 1) % textures.size();

        if (!isLoop && count >= textures.size()) {
            isOver = true;
        }
    }
}

Texture2D *Animation::updateAndGetCurrentFrame() {
    update();
    return getCurrentFrame();
}
